import os


def imageDecode(f, fn):
    dat_read = open(f, "rb")  # 读取.dat 文件
    xo = Format(f)  # 判断图片格式 并计算返回异或值
    out = target_path + '\\' + fn + ".jpg"  # 图片输出路径
    print("文件输出路径{}".format(out), end='\n\n')
    png_write = open(out, "wb")  # 图片写入
    dat_read.seek(0)  # 重置文件指针位置

    for now in dat_read:  # 循环字节
        for nowByte in now:
            newByte = nowByte ^ xo  # 转码计算
            png_write.write(bytes([newByte]))  # 转码后重新写入

    dat_read.close()
    png_write.close()


def findFile(dat_path):
    fsinfo = os.listdir(dat_path)
    for dat_file_name in fsinfo:
        temp_path = os.path.join(dat_path, dat_file_name)
        if not os.path.isdir(temp_path):
            if dat_file_name.endswith(".dat") and "Image" in temp_path:
                print('文件路径: {}' .format(temp_path))
                imageDecode(temp_path, dat_file_name)
            else:
                pass
        else:
            findFile(temp_path)


def Format(f):
    """
    计算异或值
    各图片头部信息
    jpeg：ff d8 ff
    png：89 50 4e 47
    gif： 47 49 46 38
        """
    dat_r = open(f, "rb")

    try:
        a = [(0x89, 0x50, 0x4e), (0x47, 0x49, 0x46), (0xff, 0xd8, 0xff)]
        for now in dat_r:
            for xor in a:
                i = 0
                res = []
                nowg = now[:3]  # 取前三个 数据信息
                for nowByte in nowg:
                    res.append(nowByte ^ xor[i])  # 进行判断
                    i += 1
                if res[0] == res[1] == res[2]:  # 三次异或值想等 说明就是那种格式
                    return res[0]  # 返回异或值
    except:
        pass
    finally:
        dat_r.close()


if __name__ == '__main__':
    # 修改.dat文件的存放路径
    dat_path = r'C:\Users\pc\Documents\WeChat Files\wxid_4s2g2inx5cc221\FileStorage\MsgAttach\0e6e3a602fa0b445a62313bb5ac38c5d'

    # 修改转换成png图片后的存放路径
    target_path = r'D:\tmp'

    findFile(dat_path)
    print("end")